package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.mapper.MenuMapper;
import com.example.mapper.UsersMapper;
import com.example.pojo.LoginUser;
import com.example.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/*
 *  @author 雨安
 *  类名： UserDetailsService
 *  创建时间：2024/3/18
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    //装配sql
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //创建条件构造器
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        //设置条件
        wrapper.eq(Users::getUserName,username);
        //查询用户信息
        Users user = usersMapper.selectOne(wrapper);
        //判断user是否为null判断是否查询到了用户
        if (Objects.isNull(user)){
            //返回null
            throw new RuntimeException("用户名或者密码错误");
        }
        //TODO 查询对应的权限信息 已完成
        List<String> list = menuMapper.selectPermByUserId(user.getUid());
        //把数据封装成 UserDetails对象返回
        return new LoginUser(user,list);
    }
}
